package com.gyp.config;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.gyp.enums.HwExceptionEnum;
import com.gyp.exception.RpcException;
import com.gyp.manager.PersonManager;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

@Configuration
@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {


    @Override
    public Exception decode(String s, Response response) {
        // 自定义异常
        RuntimeException exception = null;
        String json = null;
        try {
            // 获取原始的返回内容
            json = Util.toString(response.body().asReader());
            log.error("华为云接口访问异常:{}",json);
            JSONObject jsonObject = JSONObject.parseObject(json);
            String errorCode = jsonObject.getString("error_code");
            if(StringUtils.isNotBlank(errorCode)){
                HwExceptionEnum value = HwExceptionEnum.getValue(errorCode);
                if(Objects.nonNull(value)){
                    if(value.equals(HwExceptionEnum.TOKEN_MUST_UPDATE)){
                        //清除redis token
                        SpringUtil.getBean(PersonManager.class).clearToken();
                        return new RpcException("10001",value.getMsg());
                    }
                    //能在枚举里配置的异常都是业务异常
                    return new RpcException("10001",value.getMsg());
                }
                return new RpcException(errorCode,jsonObject.getString("error_msg"));
            }
            //否则抛出运行时异常
            exception = new RuntimeException(json);
        } catch (Exception ex) {
            //出现异常抛出原始的json数据
            return new RuntimeException(json);
        }
        return exception;
    }
}
